use iced::{Element, Length, Color};
use iced::widget::{text_editor, container, column, row, text, scrollable};
use crate::theme::CdbTheme;

/// SQL语法高亮器
#[derive(Debug, Clone)]
pub struct SqlHighlighter {
    keywords: Vec<&'static str>,
    functions: Vec<&'static str>,
    operators: Vec<&'static str>,
}

impl SqlHighlighter {
    pub fn new() -> Self {
        Self {
            keywords: vec![
                "SELECT", "FROM", "WHERE", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP",
                "ALTER", "TABLE", "INDEX", "VIEW", "DATABASE", "SCHEMA", "PRIMARY", "KEY",
                "FOREIGN", "REFERENCES", "CONSTRAINT", "NOT", "NULL", "UNIQUE", "DEFAULT",
                "AUTO_INCREMENT", "IDENTITY", "SEQUENCE", "TRIGGER", "PROCEDURE", "FUNCTION",
                "BEGIN", "END", "IF", "ELSE", "WHILE", "FOR", "LOOP", "RETURN", "DECLARE",
                "SET", "EXEC", "EXECUTE", "CALL", "UNION", "JOIN", "INNER", "LEFT", "RIGHT",
                "FULL", "OUTER", "ON", "AS", "DISTINCT", "ORDER", "BY", "GROUP", "HAVING",
                "LIMIT", "OFFSET", "TOP", "WITH", "CASE", "WHEN", "THEN", "ELSE", "END",
                "AND", "OR", "IN", "EXISTS", "BETWEEN", "LIKE", "IS", "ISNULL", "COALESCE",
            ],
            functions: vec![
                "COUNT", "SUM", "AVG", "MIN", "MAX", "ROUND", "FLOOR", "CEIL", "ABS",
                "UPPER", "LOWER", "TRIM", "LTRIM", "RTRIM", "SUBSTRING", "LENGTH", "CONCAT",
                "REPLACE", "CHARINDEX", "PATINDEX", "LEFT", "RIGHT", "REVERSE", "STUFF",
                "GETDATE", "DATEADD", "DATEDIFF", "DATEPART", "YEAR", "MONTH", "DAY",
                "CAST", "CONVERT", "ISNULL", "NULLIF", "COALESCE", "IIF", "CHOOSE",
            ],
            operators: vec![
                "=", "!=", "<>", "<", ">", "<=", ">=", "+", "-", "*", "/", "%", "||",
            ],
        }
    }

    /// 检查是否为SQL关键字
    pub fn is_keyword(&self, word: &str) -> bool {
        self.keywords.contains(&word.to_uppercase().as_str())
    }

    /// 检查是否为SQL函数
    pub fn is_function(&self, word: &str) -> bool {
        self.functions.contains(&word.to_uppercase().as_str())
    }

    /// 检查是否为操作符
    pub fn is_operator(&self, word: &str) -> bool {
        self.operators.contains(&word)
    }

    /// 获取语法高亮的颜色
    pub fn get_highlight_color(&self, word: &str, theme: &CdbTheme) -> Color {
        if self.is_keyword(word) {
            Color::from_rgb(0.3, 0.6, 1.0) // 蓝色 - SQL关键字
        } else if self.is_function(word) {
            Color::from_rgb(0.8, 0.4, 0.8) // 紫色 - SQL函数
        } else if self.is_operator(word) {
            Color::from_rgb(1.0, 0.6, 0.2) // 橙色 - 操作符
        } else if word.starts_with('\'') && word.ends_with('\'') {
            Color::from_rgb(0.4, 0.8, 0.4) // 绿色 - 字符串
        } else if word.chars().all(|c| c.is_ascii_digit() || c == '.') {
            Color::from_rgb(0.9, 0.7, 0.3) // 黄色 - 数字
        } else {
            theme.colors.foreground // 默认颜色
        }
    }
}

/// SQL编辑器组件
#[derive(Debug)]
pub struct SqlEditor {
    content: text_editor::Content,
    highlighter: SqlHighlighter,
    line_numbers: bool,
    auto_indent: bool,
}

impl SqlEditor {
    pub fn new() -> Self {
        Self {
            content: text_editor::Content::new(),
            highlighter: SqlHighlighter::new(),
            line_numbers: true,
            auto_indent: true,
        }
    }

    /// 设置SQL内容
    pub fn with_content(mut self, content: &str) -> Self {
        self.content = text_editor::Content::with_text(content);
        self
    }

    /// 启用/禁用行号显示
    pub fn with_line_numbers(mut self, enabled: bool) -> Self {
        self.line_numbers = enabled;
        self
    }

    /// 启用/禁用自动缩进
    pub fn with_auto_indent(mut self, enabled: bool) -> Self {
        self.auto_indent = enabled;
        self
    }

    /// 获取当前内容
    pub fn content(&self) -> &text_editor::Content {
        &self.content
    }

    /// 获取文本内容
    pub fn text(&self) -> String {
        self.content.text()
    }

    /// 格式化SQL
    pub fn format_sql(&mut self) {
        let formatted = self.format_sql_text(&self.content.text());
        self.content = text_editor::Content::with_text(&formatted);
    }

    /// SQL格式化逻辑
    pub fn format_sql_text(&self, sql: &str) -> String {
        let mut formatted = String::new();
        let mut indent_level: i32 = 0;

        // 将单行SQL分解为多行
        let sql_upper = sql.to_uppercase();
        let mut tokens = Vec::new();

        // 简单的关键字分割
        let keywords = ["SELECT", "FROM", "WHERE", "ORDER BY", "GROUP BY", "HAVING", "INSERT", "UPDATE", "DELETE"];
        let mut current_pos = 0;

        for keyword in &keywords {
            if let Some(pos) = sql_upper.find(keyword) {
                if pos >= current_pos {
                    if current_pos < pos {
                        tokens.push(&sql[current_pos..pos]);
                    }
                    let end_pos = pos + keyword.len();
                    tokens.push(&sql[pos..end_pos]);
                    current_pos = end_pos;
                }
            }
        }

        // 添加剩余部分
        if current_pos < sql.len() {
            tokens.push(&sql[current_pos..]);
        }

        // 如果没有找到关键字，按空格分割
        if tokens.is_empty() {
            tokens = sql.split_whitespace().collect();
        }

        for (i, token) in tokens.iter().enumerate() {
            let trimmed = token.trim();
            if trimmed.is_empty() {
                continue;
            }

            let token_upper = trimmed.to_uppercase();

            // 主要关键字换行
            if token_upper.starts_with("SELECT")
                || token_upper.starts_with("FROM")
                || token_upper.starts_with("WHERE")
                || token_upper.starts_with("ORDER BY")
                || token_upper.starts_with("GROUP BY") {
                if i > 0 {
                    formatted.push('\n');
                }
                // 添加缩进
                for _ in 0..indent_level {
                    formatted.push_str("    ");
                }
            }

            formatted.push_str(trimmed);

            // 在关键字后添加空格
            if !trimmed.ends_with(' ') && i < tokens.len() - 1 {
                formatted.push(' ');
            }
        }

        // 确保至少有一个换行符
        if !formatted.contains('\n') && formatted.len() > 20 {
            // 在FROM前添加换行
            if let Some(pos) = formatted.to_uppercase().find("FROM") {
                formatted.insert(pos, '\n');
            }
        }

        formatted
    }

    /// 渲染编辑器
    pub fn view<'a, Message>(&'a self, theme: &CdbTheme) -> Element<'a, Message>
    where
        Message: Clone + 'a,
    {
        let editor = text_editor(&self.content)
            .placeholder("输入SQL查询...")
            .size(14)
            .padding(10);

        if self.line_numbers {
            let line_count = self.content.text().lines().count().max(1);
            let line_numbers = self.create_line_numbers(line_count, theme);

            row![
                line_numbers,
                editor
            ]
            .spacing(5)
            .into()
        } else {
            editor.into()
        }
    }

    /// 创建行号显示
    fn create_line_numbers<'a, Message>(&self, line_count: usize, theme: &CdbTheme) -> Element<'a, Message>
    where
        Message: Clone + 'a,
    {
        let mut line_numbers = column![];

        for i in 1..=line_count {
            line_numbers = line_numbers.push(
                text(format!("{:3}", i))
                    .size(12)
                    .color(theme.colors.muted_foreground)
            );
        }

        container(
            scrollable(line_numbers)
                .width(Length::Fixed(40.0))
        )
        .style(|theme: &iced::Theme| {
            container::Style {
                background: Some(Color::from_rgb(0.1, 0.1, 0.1).into()),
                border: iced::Border {
                    color: Color::from_rgb(0.2, 0.2, 0.2),
                    width: 1.0,
                    radius: 0.0.into(),
                },
                ..Default::default()
            }
        })
        .padding(5)
        .into()
    }
}

impl Default for SqlEditor {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sql_highlighter_keywords() {
        let highlighter = SqlHighlighter::new();
        
        assert!(highlighter.is_keyword("SELECT"));
        assert!(highlighter.is_keyword("select"));
        assert!(highlighter.is_keyword("FROM"));
        assert!(!highlighter.is_keyword("table_name"));
    }

    #[test]
    fn test_sql_highlighter_functions() {
        let highlighter = SqlHighlighter::new();
        
        assert!(highlighter.is_function("COUNT"));
        assert!(highlighter.is_function("count"));
        assert!(highlighter.is_function("SUM"));
        assert!(!highlighter.is_function("my_function"));
    }

    #[test]
    fn test_sql_editor_creation() {
        let editor = SqlEditor::new();
        assert!(editor.line_numbers);
        assert!(editor.auto_indent);
        // text_editor::Content may add a newline by default
        assert!(editor.text().is_empty() || editor.text() == "\n");
    }

    #[test]
    fn test_sql_editor_with_content() {
        let sql = "SELECT * FROM users";
        let editor = SqlEditor::new().with_content(sql);
        // text_editor::Content may add a newline
        assert!(editor.text() == sql || editor.text() == format!("{}\n", sql));
    }

    #[test]
    fn test_sql_formatting() {
        let editor = SqlEditor::new();
        let sql = "select id,name from users where age>18";
        let formatted = editor.format_sql_text(sql);

        // Check that formatting preserves the original keywords (case may vary)
        assert!(formatted.to_lowercase().contains("select"));
        assert!(formatted.to_lowercase().contains("from"));
        assert!(formatted.to_lowercase().contains("where"));
        // Check that formatting produces multiple lines (basic formatting)
        assert!(formatted.lines().count() > 1);
    }
}
